import streamlit as st
import dashscope
import pyttsx3
from click import prompt
from dashscope import Generation
from sympy.physics.units import sr
# 1.配置api密钥
dashscope.api_key = "sk-ec38daeb0ceb42c1a580a70316c64717"

# 调用千问大模型2.5
def text_generation(input_text):
    response = Generation.call(
        model="qwen2.5-1.5b-instruct",
        prompt=input_text,
    )
    if response.status_code == 200:  # 响应成功
        return response.output.text
    else:
        return None
# 语音转文本
def get_text():
    import speech_recognition as sr
    # 1.创建识别器
    r = sr.Recognizer()
    # 2.使用麦克风录制声音
    with sr.Microphone() as source:
        print("开始录音")
        audio = r.listen(source)
    try:
        text1 = r.recognize_whisper(audio, language='chinese')
        print(f"识别结果:{text1}")
        return text1
    except Exception as e:
        print("无法识别", e)
        return None

def main():
    if 'shared_text' not in st.session_state:
        st.session_state.shared_text = ""
    if 'recording_status' not in st.session_state:
        st.session_state.recording_status = ""
    st.session_state.shared_text = st.text_area(
        "文本内容",
        value=st.session_state.shared_text,
        height=100
    )
    col1, col2, col3 = st.columns(3)
    with col1:
        t_r_bt = st.button("文本转语音", key="t_r_button")
    with col2:
        r_t_bt = st.button("语音转文本", key="r_t_button")
    with col3:
        talk_bt = st.button("语音与大模型交流", key="talk_button")
    # 文本转语音
    if t_r_bt:
        if not st.session_state.shared_text.strip():
            st.warning("请先输入文本内容")
        else:
            engine = pyttsx3.init()
            engine.say(st.session_state.shared_text)
            engine.runAndWait()
            st.success("语音播放完成!")
    # 语音转文本
    if r_t_bt:
        st.session_state.recording_status = "正在录音"
        st.info(st.session_state.recording_status)
        text1 = get_text()
        st.session_state.recording_status = ""
        st.session_state.shared_text = ""
        if text1:
            st.session_state.shared_text = text1
            st.success("语音识别成功!")
        else:
            st.error("语音识别失败，请重试")
    # 语音与大模型交流功能
    if talk_bt:
        st.session_state.recording_status = "正在录音，请说话..."
        st.info(st.session_state.recording_status)
        text2 = get_text()
        st.session_state.recording_status = ""
        st.session_state.shared_text = ""
        if not text2:
            st.error("语音识别失败")
        else:
            st.session_state.shared_text = text2
            response_text = text_generation(text2)
            if response_text:
                st.write("\n千问大模型回复:")
                st.write(response_text)
                text = f"识别结果：{text2} 。 回答：{response_text}"
                st.session_state.shared_text = text
                engine = pyttsx3.init()
                engine.say(response_text)
                engine.runAndWait()
                st.success("语音回复播放完成!")
            else:
                st.error("大模型请求失败")

if __name__ == '__main__':
    main()
